package com.test.system.admin;

import com.test.system.admin.dao.MenuDao;
import com.test.system.admin.dao.PermDao;
import com.test.system.admin.shiro.MyShiroFilterFactoryBean;
import com.test.system.admin.shiro.MyShiroRealm;
import com.test.system.admin.shiro.MyShiroRoleFilter;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Configuration
public class ShiroConfig {
    @Bean
    public MyShiroRealm myShiroRealm() {
        return new MyShiroRealm();
    }

    @Bean
    public MemoryConstrainedCacheManager cacheManager() {
        return new MemoryConstrainedCacheManager();
    }

    @Bean
    public DefaultWebSecurityManager securityManager(MyShiroRealm myShiroRealm, MemoryConstrainedCacheManager cacheManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm);
        securityManager.setCacheManager(cacheManager);
        return securityManager;
    }

    @Bean
    public MyShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager, MenuDao menuDao, PermDao permDao) {
        MyShiroFilterFactoryBean shiroFilterFactoryBean = new MyShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("go_login.html");
        shiroFilterFactoryBean.setUnauthorizedUrl("error.html");
        shiroFilterFactoryBean.setMenuDao(menuDao);
        shiroFilterFactoryBean.setPermDao(permDao);
        shiroFilterFactoryBean.setFilterChainDefinitions("/login.html=anon\n/go_login.html=anon\n/static/**=anon");
        Map<String,Filter> filterMap=new HashMap<>();
        filterMap.put("roles",new MyShiroRoleFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 让权限注解生效
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
